package com.inxedu.os.edu.controller.statistics;

import com.inxedu.os.edu.pojo.*;
import com.inxedu.os.edu.service.statistics.CourseKpointStatisticsService;
import com.inxedu.os.edu.service.statistics.CourseStatisticsService;
import com.inxedu.os.edu.service.statistics.MainSystemStatistics;
import com.inxedu.os.edu.service.statistics.UserStatisticsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@Api(tags = "统计")
public class StatisticsController {
    @Autowired
    private MainSystemStatistics mainSystemStatistics;

    @Autowired
    private UserStatisticsService userStatisticsService;

    @Autowired
    private CourseKpointStatisticsService courseKpointStatisticsService;

    @Autowired
    private CourseStatisticsService courseStatisticsService;

    /**
     * 生成统计页面跳转
     */
    @ApiOperation(value = "生成统计页面跳转",notes = "生成统计页面跳转")
    @RequestMapping("admin/jumpGenerationStatisticsPage")
    public String toStatistics(){
        return "/view/inxedu/admin/statistics/generation_statistics";
    }
    /**
     * 每日学员数统计页面跳转
     * @return
     */
    @ApiOperation(value = "每日学员数统计页面跳转",notes = "每日学员数统计页面跳转")
    @RequestMapping("admin/statisticsPage/dailyUserNumber")
    public String toMain(HttpServletRequest httpServletRequest){
        httpServletRequest.setAttribute("type","dailyUserNumber");
        return "view/inxedu/admin/statistics/statistical_chart";
    }
    /**
     * 每日课程数统计页面跳转
     */
    @ApiOperation(value = "每日课程数统计页面跳转",notes = "每日课程数统计页面跳转")
    @RequestMapping("admin/statisticsPage/dailyCourseNumber")
    public String courseStatisticsPage(HttpServletRequest httpServletRequest){
        httpServletRequest.setAttribute("type","dailyCourseNumber");
        return "view/inxedu/admin/statistics/statistical_chart";
    }
    /**
     * 每日学员登录数统计
     */
    @ApiOperation(value = "每日学员登录数统计页面跳转",notes = "每日学员登录数统计页面跳转")
    @RequestMapping("admin/statisticsPage/login")
    public String loginStatisticsPagge(HttpServletRequest httpServletRequest){
        httpServletRequest.setAttribute("type","login");
        return "view/inxedu/admin/statistics/statistical_chart";
    }
    /**
     * 每日学员注册数统计
     */
    @ApiOperation(value = "每日学员注册数统计页面跳转",notes = "每日学员注册数统计页面跳转")
    @RequestMapping("admin/statisticsPage/registered")
    public String registeredStatisticsPage(HttpServletRequest httpServletRequest){
        httpServletRequest.setAttribute("type","registered");
        return "view/inxedu/admin/statistics/statistical_chart";
    }
    /**
     * 视频观看数统计
     */
    @ApiOperation(value = "视频观看数统计页面跳转",notes = "视频观看数统计页面跳转")
    @RequestMapping("admin/statisticsPage/videoViewingNum")
    public String videoStatisticsPage(HttpServletRequest httpServletRequest){
        httpServletRequest.setAttribute("type","videoViewingNum");
        return "view/inxedu/admin/statistics/statistical_chart";
    }

    /**
     * 判断时间相差天数方法
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return
     */

    public String[] timeDifference(String startDate,String endDate){
        String[] split = startDate.split("-");
        String[] split1 = endDate.split("-");
        int endDateYear= Integer.parseInt(split1[0]);
        int endDateMonth = Integer.parseInt(split1[1]);
        int endDateDay = Integer.parseInt(split1[2]);
        Calendar instance = Calendar.getInstance();
        instance.set(Integer.parseInt(split[0]),Integer.parseInt(split[1])-1,Integer.parseInt(split[2]));
        List<String> list = new ArrayList();
        SimpleDateFormat format = new SimpleDateFormat("MM月dd");
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy");
        list.add(format.format(instance.getTime()));
        while (true){
            instance.add(Calendar.DATE,1);
            Date time = instance.getTime();
            list.add(format.format(time));
            if(Integer.parseInt(format1.format(time))==endDateYear&&time.getMonth()+1==endDateMonth&&time.getDate()==endDateDay){
                break;
            }
        }
        String[] strings = new  String[list.size()];
        String[] objects =  list.toArray(strings);
        return objects;
    }

    /**
     * 从数组中找响应数据在数组中的下标
     * @param objects 数组
     * @param object 相应数据
     * @return
     */

    public int selectLocationFromArray(@NotNull Object [] objects,@NotNull Object object){
        for (int i = 0 ; i<objects.length;i++){
            if(objects[i]!=null){
                if(objects[i].equals(object)){
                    return i;
                }
            }
        }
        return 0;
    }

    /**
     * 生成近七天的开始时间和结束时间
     * @return
     */

    private String[] SevenDayDate(){
        Date date = new Date();
        Calendar instance = Calendar.getInstance();
        instance.setTime(date);
        instance.add(Calendar.DATE,-7);
        SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd");
        String startDate = simpleDateFormat.format(date);
        String endDate = simpleDateFormat.format(instance.getTime());
        String []string=new String[2];
        string[0]=endDate;
        string[1]=startDate;
        return string;
    }
    /**
     * 学员登录数统计方法
     * @param type
     * @param startDate
     * @param endDate
     */
    @ApiOperation(value = "学员登录数统计",notes = "统计学院登录数量")
    @ApiImplicitParams({@ApiImplicitParam(name = "startDate",dataType = "String",required = false,value = "统计的开始时间,如果为空则默认统计近七天的数据,要求格式为yyyy-MM-dd",defaultValue = "null",paramType = "qury")
    ,@ApiImplicitParam(name = "endDate",dataType = "String",required = false,value = "统计的结束时间",defaultValue = "null",paramType = "qury")})
    @RequestMapping(value = "admin/ajax/statistics/login",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Map<String,Object> loginSelectStatistics(HttpServletRequest httpServletRequest, @RequestParam("type") String type, String startDate, String endDate, ModelAndView modelAndView){
        if(startDate==null||endDate==null||startDate.isEmpty()||endDate.isEmpty()){
            String[] strings = this.SevenDayDate();
            startDate = strings[0];
            endDate = strings[1];
        }
        List<EduStatisticsDay> eduStatisticsDays = mainSystemStatistics.selectMessageSomeTimesAgo(startDate, endDate);
        //时间轴数组
        String[] showDate = this.timeDifference(startDate, endDate);
        //统计数据数组
        int[] data = new int[showDate.length];
        SimpleDateFormat format = new SimpleDateFormat("MM月dd");
        Calendar instance = Calendar.getInstance();
        //处理数组
        for (int i = 0; i<eduStatisticsDays.size();i++){
            EduStatisticsDay eduStatisticsDay = eduStatisticsDays.get(i);
            instance.setTime(eduStatisticsDay.getStatisticsTime());
            instance.add(Calendar.DATE,-1);
            int i1 = this.selectLocationFromArray(showDate, format.format(instance.getTime()));
            if(i1>=0){
                data[i1] = eduStatisticsDay.getLoginNum();
            }
        }
        //处理今天的学员登记统计数据
        List<EduUser> eduUsers = userStatisticsService.selectCreateTimeToday();
        showDate[showDate.length-1] = format.format(new Date());
        data[showDate.length-1] = 0;
        if (eduUsers!=null){
            data[showDate.length-1] = eduUsers.size();
        }
        Map<String,Object> map = new HashMap<>();
        map.put("showDate",showDate);
        map.put("data",data);
        map.put("startDate",startDate);
        map.put("endDate",endDate);
        map.put("type",type);
        return map;
    }

    /**
     * 学员注册数统计方法
     * @param type
     * @param startDate
     * @param endDate
     */
    @ApiOperation(value = "学员注册数统计",notes = "统计学院注册数量")
    @ApiImplicitParams({@ApiImplicitParam(name = "startDate",dataType = "String",required = false,value = "统计的开始时间,如果为空则默认统计近七天的数据,要求格式为yyyy-MM-dd",defaultValue = "null",paramType = "qury")
    ,@ApiImplicitParam(name = "endDate",dataType = "String",required = false,value = "统计的结束时间",defaultValue = "null",paramType = "qury")})
    @RequestMapping(value = "admin/ajax/statistics/registered",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Map<String,Object>  registeredSelectStatistics(HttpServletRequest httpServletRequest,String type, String startDate, String endDate,ModelAndView modelAndView){
        if(startDate==null||endDate==null||startDate.isEmpty()||endDate.isEmpty()){
            String[] strings = this.SevenDayDate();
            startDate = strings[0];
            endDate = strings[1];
        }
        List<EduStatisticsDay> eduStatisticsDays = mainSystemStatistics.selectRegisteredNumBefore(startDate, endDate);
        //时间轴数组
        String[] showDate = this.timeDifference(startDate, endDate);
        //统计数据数组
        int[] data = new int[showDate.length];
        SimpleDateFormat format = new SimpleDateFormat("MM月dd");
        Calendar instance = Calendar.getInstance();
        //处理数组
        for (int i = 0; i<eduStatisticsDays.size();i++){
            EduStatisticsDay eduStatisticsDay = eduStatisticsDays.get(i);
            instance.setTime(eduStatisticsDay.getStatisticsTime());
            instance.add(Calendar.DATE,-1);
            int i1 = this.selectLocationFromArray(showDate, format.format(instance.getTime()));
            if(i1>=0){
                data[i1] = eduStatisticsDay.getRegisteredNum();
            }
        }
        //处理今天学院注册数统计
        List<EduUserLoginLog> eduUserLoginLogs = mainSystemStatistics.selectUserLoginToDay();
        showDate[showDate.length-1] = format.format(new Date());
        data[showDate.length-1] = 0;
        if (eduUserLoginLogs!=null){
            data[showDate.length-1] = eduUserLoginLogs.size();
        }
        Map<String,Object> map = new HashMap<>();
        map.put("showDate",showDate);
        map.put("data",data);
        map.put("startDate",startDate);
        map.put("endDate",endDate);
        map.put("type",type);
        return map;
    }

    /**
     * 视频观看数统计方法
     * @param type
     * @param startDate
     * @param endDate
     */

    @ApiOperation(value = "视频观看数统计",notes = "统计视频观看数量")
    @ApiImplicitParams({@ApiImplicitParam(name = "startDate",dataType = "String",required = false,value = "统计的开始时间,如果为空则默认统计近七天的数据,要求格式为yyyy-MM-dd",defaultValue = "null",paramType = "qury")
    ,@ApiImplicitParam(name = "endDate",dataType = "String",required = false,value = "统计的结束时间",defaultValue = "null",paramType = "qury")})
    @RequestMapping(value = "admin/ajax/statistics/videoViewingNum",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Map<String,Object>  videoViewingNumSelectStatistics(String type, String startDate, String endDate){
        if(startDate==null||endDate==null||startDate.isEmpty()||endDate.isEmpty()){
            String[] strings = this.SevenDayDate();
            startDate = strings[0];
            endDate = strings[1];
        }
        List<EduStatisticsDay> eduStatisticsDays = mainSystemStatistics.selectVideoVieWingNumBefore(startDate, endDate);
        //时间轴数组
        String[] showDate = this.timeDifference(startDate, endDate);
        //统计数据数组
        int[] data = new int[showDate.length];
        SimpleDateFormat format = new SimpleDateFormat("MM月dd");
        Calendar instance = Calendar.getInstance();
        //处理数组
        int count=0;
        for (int i = 0; i<showDate.length;i++){
            for (com.inxedu.os.edu.pojo.EduStatisticsDay EduStatisticsDay:
                    eduStatisticsDays) {
                instance.setTime(EduStatisticsDay.getStatisticsTime());
                instance.add(Calendar.DATE,-1);
                if(showDate[i].equals(format.format(instance.getTime()))){
                    count = EduStatisticsDay.getVideoViewingNum();
                    data[i] = count;
                }else {
                    data[i] = count;
                }
            }
        }
        //处理今天的视频播放数统计
        int i = courseKpointStatisticsService.selectPlayCountNum();
        Map<String,Object> map = new HashMap<>();
        map.put("showDate",showDate);
        map.put("data",data);
        map.put("startDate",startDate);
        map.put("endDate",endDate);
        map.put("type",type);
        System.out.println(map);
        return map;
    }

    /**
     * 每日学员数统计方法
     * @param type
     * @param startDate
     * @param endDate
     */
    @ApiOperation(value = "每日学员数统计",notes = "统计每天学员总数量")
    @ApiImplicitParams({@ApiImplicitParam(name = "startDate",dataType = "String",required = false,value = "统计的开始时间,如果为空则默认统计近七天的数据,要求格式为yyyy-MM-dd",defaultValue = "null",paramType = "qury")
    ,@ApiImplicitParam(name = "endDate",dataType = "String",required = false,value = "统计的结束时间",defaultValue = "null",paramType = "qury")})
    @RequestMapping(value = "admin/ajax/statistics/dailyUserNumber",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Map<String,Object>  dailyUserNumberSelectStatistics(HttpServletRequest httpServletRequest,ModelAndView modelAndView,String type, String startDate,String endDate){
        if(startDate==null||endDate==null||startDate.isEmpty()||endDate.isEmpty()){
            String[] strings = this.SevenDayDate();
            startDate = strings[0];
            endDate = strings[1];
        }
        List<EduStatisticsDay> eduStatisticsDays = mainSystemStatistics.selectDailyUserNumberBefore(startDate, endDate);
        //时间轴数组
        String[] showDate = this.timeDifference(startDate, endDate);
        //统计数据数组
        int[] data = new int[showDate.length];
        SimpleDateFormat format = new SimpleDateFormat("MM月dd");
        Calendar instance = Calendar.getInstance();
        //处理数组
        int count=0;
        for (int i = 0; i<showDate.length;i++){
            for (com.inxedu.os.edu.pojo.EduStatisticsDay EduStatisticsDay:
                    eduStatisticsDays) {
                instance.setTime(EduStatisticsDay.getStatisticsTime());
                instance.add(Calendar.DATE,-1);
                if(showDate[i].equals(format.format(instance.getTime()))){
                    count = EduStatisticsDay.getDailyUserNumber();
                    data[i] = count;
                }else{
                    data[i] = count;
                }
            }
        }
        //处理今天的用户总数
        List<EduUserLoginLog> eduUserLoginLogs = mainSystemStatistics.selectUserLoginToDay();
        showDate[showDate.length-1] = format.format(new Date());
        data[showDate.length-1] = 0;
        if (eduUserLoginLogs!=null){
            data[showDate.length-1] = eduUserLoginLogs.size()+count;
        }else {
            data[showDate.length-1] = count;
        }
        Map<String,Object> map = new HashMap<>();
        map.put("showDate",showDate);
        map.put("data",data);
        map.put("startDate",startDate);
        map.put("endDate",endDate);
        map.put("type",type);
        return map;
    }

    /**
     * 每日课程数统计
     * @param type
     * @param startDate
     * @param endDate
     */
    @ApiOperation(value = "每日课程数",notes = "统计每天课程总数量")
    @ApiImplicitParams({@ApiImplicitParam(name = "startDate",dataType = "String",required = false,value = "统计的开始时间,如果为空则默认统计近七天的数据,要求格式为yyyy-MM-dd",defaultValue = "null",paramType = "qury")
    ,@ApiImplicitParam(name = "endDate",dataType = "String",required = false,value = "统计的结束时间",defaultValue = "null",paramType = "qury")})
    @RequestMapping(value = "admin/ajax/statistics/dailyCourseNumber",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Map<String, Object>  dailyCourseNumberSelectStatistics(ModelAndView modelAndView, HttpServletRequest httpServletRequest, String type, String startDate, String endDate){
        if(startDate==null||endDate==null||startDate.isEmpty()||endDate.isEmpty()){
            String[] strings = this.SevenDayDate();
            startDate = strings[0];
            endDate = strings[1];
        }
        List<EduStatisticsDay> eduStatisticsDays = mainSystemStatistics.selectDailyCourseNumberBefore(startDate, endDate);
        //时间轴数组
        String[] showDate = this.timeDifference(startDate, endDate);
        //统计数据数组
        int[] data = new int[showDate.length];
        SimpleDateFormat format = new SimpleDateFormat("MM月dd");
        Calendar instance = Calendar.getInstance();
        //处理数组
        int count=0;
        for (int i = 0; i<showDate.length;i++){
            for (com.inxedu.os.edu.pojo.EduStatisticsDay EduStatisticsDay:
                    eduStatisticsDays) {
                instance.setTime(EduStatisticsDay.getStatisticsTime());
                instance.add(Calendar.DATE,-1);
                if(showDate[i].equals(format.format(instance.getTime()))){
                    count = EduStatisticsDay.getDailyCourseNumber();
                    data[i] = count;
                }else{
                    data[i] = count;
                }
            }
        }
        //处理今天的课程总数
        List<EduCourse> eduCourses = courseStatisticsService.selectCourseCount(1);
        showDate[showDate.length-1] = format.format(new Date());
        data[showDate.length-1] = 0;
        if (eduCourses!=null){
            data[showDate.length-1] = eduCourses.size();
        }else {
            data[showDate.length-1] = count;
        }
        Map<String,Object> map = new HashMap<>();
        map.put("showDate",showDate);
        map.put("data",data);
        map.put("startDate",startDate);
        map.put("endDate",endDate);
        map.put("type",type);
        return map;
    }

    /**
     * 生成统计
     */
    @ApiOperation(value = "生成统计",notes = "从其他表中查询指定某天数据后,向数据库生成指定某天的统计,如果已经城成果则更新统计数据")
    @ApiImplicitParam(name = "statisticsTime",value = "生成统计的指定日期,要求格式为yyyy-MM-dd",dataType = "String",required = true,paramType = "qury")
    @RequestMapping(value = "admin/statistics/create/batch",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public MobResult createStatistics(@RequestParam("startTime") String statisticsTime){
        MobResult result = new MobResult();
        Date date = null ;
        int a = 500 ;
        if (statisticsTime!=null&&!statisticsTime.isEmpty()){
            String trim = statisticsTime.trim();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD");
            try {
                date = format.parse(trim);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            SimpleDateFormat SimpleDateFormat = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
            String format1 = SimpleDateFormat.format(date);
            a = mainSystemStatistics.enerateStatistics(format1);
            if(a == 0 ){
                result.setMessage("exists");
            }else {
                result.setMessage("true");
            }
        }
        return result;
    }

    /**
     * 删除统计
     */

    @ApiOperation(value = "删除数据库中的统计数据",notes = "删除指定某天的统计记录")
    @ApiImplicitParam(name = "statisticsTime",value = "删除指定统计日期的数据,要求格式为yyyy-MM-dd",dataType = "String",required = true,paramType = "qury")
    @RequestMapping(value = "admin/statistics/del/batch",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public  int  delStatistics(@RequestParam("startTime") String statisticsTime){
        Date date = null ;
        String trim = statisticsTime.trim();
        int a = 500 ;
        if (trim!=null&&!trim.isEmpty()){
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date parse = null;
            try {
                parse = format.parse(trim);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            SimpleDateFormat SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (mainSystemStatistics.delStatistics(SimpleDateFormat.format(parse))==1) {
                a = 200;
            }
        }
        return a;
    }
}
